package com.utils;

import java.util.Random;

import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;

public class ThreadWithHandler extends Thread {

    protected static final String TAG = "ThreadWithHandler";
    Handler handler = null;

    public void sendMsg(Message msg) {
        handler.sendEmptyMessage(new Random().nextInt());
    }

    public Message obtainMessage() {
        return handler.obtainMessage();
    }

    public void sendEmptyMessage(int what) {
        handler.sendEmptyMessage(what);
    }

    public void post(Runnable r) {
        handler.post(r);
    }

    @Override
    public void interrupt() {
        handler.getLooper().quit();
        super.interrupt();
    }

    public void run() {
        try {
            Looper.prepare();
            handler = new Handler(new Callback() {

                @Override
                public boolean handleMessage(Message msg) {
                    LogUtil.w(TAG, "线程" + Thread.currentThread().getId() + " 收到消息：" + msg.what);
                    try {
                        sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return false;
                }
            });
            Looper.loop();

        } finally {
            LogUtil.e(TAG, "线程" + Thread.currentThread().getId() + " 收到消息：run finish!");
        }
    }
}
